package cn.zcy.utils;

import cn.zcy.domain.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Description;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 记录日志的工具类
 */
@Component
@Aspect //表明当前类是一个切面类(切面)
@Order(2)
public class LogUtil {

    @Around(value = ("execution(public * *..*.*(..))"))
    public Object around(ProceedingJoinPoint joinPoint) {
        Object proceed = null;
        try {
            //获取参数
            Object[] args = joinPoint.getArgs();
            for (Object arg : args) {
                System.out.println("参数的名称 = " + arg);
            }

            Signature signature = joinPoint.getSignature();

            if (signature instanceof MethodSignature){
                MethodSignature methodSignature=(MethodSignature) signature;
                Method method = methodSignature.getMethod();

                String name = method.getName();

                System.out.println("方法的名称 = " + name);

                boolean annotationPresent = method.isAnnotationPresent(Description.class);
                if (annotationPresent){
                    Description annotation = method.getAnnotation(Description.class);
                    String value = annotation.value();
                    System.out.println("注解的值 = " + value);
                }
            }


            try {
                System.out.println("前置通知执行了");
                proceed = joinPoint.proceed();
            } finally {
                System.out.println("最终通知执行了");
            }
            System.out.println("后置通知执行了");
            System.out.println("返回值是=" + proceed);
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("异常通知");
            throw new RuntimeException(throwable);
        }

    }
}
